﻿using System;
using System.Runtime.InteropServices;
using UnityEngine;
using System.Collections;

public class LineOfSight : MonoBehaviour {

    public LayerMask LayerMask;
    private Light _light;
    private float _angle;
    private int _rays;
    private float _inc;
    private float _startAngle;
    private float _endAngle;
	// Use this for initialization
	void Start() {        
	    _light = GetComponent<Light>();
        _rays = 6;
	    var sa = _light.spotAngle;
        _startAngle = ((-sa/2)) + transform.localEulerAngles.z;
        _endAngle = (sa/2) + transform.localEulerAngles.z;
	    _angle = _startAngle;
	    _inc = sa / _rays;
    }

    private void Update() {
        var sa = _light.spotAngle;
        _startAngle = ((-sa / 2)) + transform.localEulerAngles.z + transform.parent.localEulerAngles.z;
        _endAngle = (sa / 2) + transform.localEulerAngles.z + transform.parent.localEulerAngles.z;
        CheckSpot();
    }

    private void CheckSpot() {
        for (int i = 0; i < _rays; i++) {
            CheckAngle(Vector3.down, _angle + _inc*i);
        }
        if (_angle + _inc*(_rays - 1) > _endAngle) _angle = _startAngle;
        if (_angle < _startAngle) _angle = _startAngle;
        else _angle += 2f;
    }

    void CheckAngle(Vector3 v, float angle) {
        var origin = _light.transform.position.ZeroZ();
        var dir = v.RotateZ(angle);
        var ray = new Ray2D(origin, dir);
        Debug.DrawRay(ray.origin, ray.direction * _light.range/2, Color.red);
        var hit = Physics2D.Raycast(ray.origin, ray.direction, _light.range/2, LayerMask);
        if(hit.collider != null) {
            var fow = hit.collider.gameObject.GetComponent<FogOfWar>();
            if(fow != null) fow.Show();
        }
    }



}
